package com.goodving.guli.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.goodving.guli.R;
import com.goodving.guli.application.GuliApplication;
import com.goodving.guli.bt.model.PersonInfo;
import com.goodving.guli.model.Keeper;
import com.goodving.guli.utility.C1481u;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.com.smartdevices.bracelet.config.C0886a;

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private CheckBox boxRememberPassword;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    private EmailCheck mEmailCheck = new EmailCheck();
    private String rememberPasswordString = null;
    private static boolean rememberPasswordStatus = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getActionBar().hide();
        setContentView(R.layout.activity_login);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        boxRememberPassword = (CheckBox)findViewById(R.id.rememberPassword);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        boxRememberPassword.setChecked(rememberPasswordStatus);
        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Fetching user details from sqlite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        if (name != null) {
            inputEmail.setText(name);
        }

        final String rememberPassword = user.get("password");

        if (rememberPassword != null && rememberPasswordStatus) {
            inputPassword.setText("******");
            rememberPasswordString = rememberPassword;
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = null;
                if (rememberPasswordString != null && boxRememberPassword.isChecked()) {
                    password = rememberPasswordString;
                } else {
                    password = inputPassword.getText().toString().trim();
                }

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    if (mEmailCheck.checkEmail(email)) {
                        checkLogin(email, password);
                    } else {
                        Toast.makeText(getApplicationContext(),
                                R.string.email_addr_invalid, Toast.LENGTH_LONG)
                                .show();
                    }
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            R.string.login_info_incomplete, Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });


        boxRememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                rememberPasswordStatus = isChecked;
            }
        });


        inputPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus){
                if (hasFocus) {
                    inputPassword.setText("");
                    rememberPasswordString = null;
                }
            }
        });
    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    // boolean error = jObj.getBoolean("error");
                    String result = jObj.getString("result");
                    boolean error = (Integer.parseInt(result) != 1);

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        JSONObject gpUser = jObj.getJSONObject("gpUser");
                        String name = gpUser.getString("loginName");
                        String email = gpUser.getString("cellphoneNumber");
                        String password = gpUser.getString("loginPassword");
                        // Now store the user in SQLite
                        Integer uid = gpUser.getInt("userId");

                        String created_at = gpUser
                                .getString("createTime");

                        // delete all old users before insert new uers;
                        db.deleteUsers();
                        // Inserting row in users table
                        db.addUser(name, email, uid.toString(), created_at, password);

                        // here we store the login in information to the Keeper.
                        if((uid != null) && (name != null)) {
                            PersonInfo readPersonInfo = Keeper.readPersonInfo();
                            // to check if this is a new person
                            if (!(readPersonInfo.nickname.equals(name) && (readPersonInfo.uid == uid))) {
                                readPersonInfo = new PersonInfo();
                                readPersonInfo.nickname = name;
                                readPersonInfo.uid = uid;
                                Keeper.keepPersonInfo(readPersonInfo);
                            }
                            // keep login status
                            C0886a.m9063a(C1481u.getContext(), uid, null);
                        }

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("loginName", email);
                params.put("loginPassword", password);

                return params;
            }

        };

        // Adding request to request queue
        GuliApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}